package com.sdry.product.sorting.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.sdry.basic.entity.Container;
import com.sdry.basic.entity.Material;
import com.sdry.basic.entity.ProductionStation;
import com.sdry.basic.entity.WarehousesRegionLocation;
import com.sdry.common.BaseAPIMessageTypeEnum;
import com.sdry.exception.BizException;
import com.sdry.product.prod.entity.ResultAppList;
import com.sdry.product.sorting.entity.SortFrame;
import com.sdry.product.sorting.entity.SortReceiving;
import com.sdry.product.sorting.entity.SortReceivingDetail;
import com.sdry.product.sorting.entity.SortingApp;
import com.sdry.product.sorting.mapper.SortReceivingDetailMapper;
import com.sdry.product.sorting.mapper.SortReceivingMapper;
import com.sdry.product.sorting.mapper.SortingAppServiceMapper;
import com.sdry.product.sorting.mapper.SortingStockMapper;
import com.sdry.transit.entity.TransitLoading;
import com.sdry.untils.CustomUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * APP分拣接口
 * @author chenBin
 * @date 2020年3月18日 14:43:09
 * @version 1.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SortingAppServiceImpl implements SortingAppService{

    @Resource
    private SortingAppServiceMapper sortingAppServiceMapper;

    @Resource
    private SortReceivingDetailMapper sortReceivingDetailMapper;

    @Resource
    private SortingStockMapper sortingStockMapper;

    @Resource
    private SortReceivingMapper sortReceivingMapper;

    @Resource
    private SortingStockService sortingStockService;

    /**
     * 查询卸车收货的生产单据查询
     * @return HashMap<String, Object>
     */
    @Override
    public List<SortingApp> queryTransitLoadingDetailNumber() {
        List<SortingApp> newSortingApps = new ArrayList<>();
        //如果编号里面没有东西，没有框编号，说明已经收货完成
        List<SortingApp> sortingApps = sortingAppServiceMapper.queryTransitLoadingDetailNumber();
        for (SortingApp sortingApp : sortingApps) {
            List<ProductionStation> productionStations = sortingAppServiceMapper.querySortingContainerNumber(sortingApp.getCpLate(), sortingApp.getToNumber());
            if (productionStations.size() > 0){
                newSortingApps.add(sortingApp);
            }
        }
        return newSortingApps;
    }

    /**
     * 查询容器分拣区卸车收货编号
     * @param carNumber 车牌
     * @param toNumber  编号
     * @return List<ProductionStation>
     */
    @Override
    public List<ProductionStation> querySortingContainerNumber(String carNumber, String toNumber) {
        return sortingAppServiceMapper.querySortingContainerNumber(carNumber,toNumber);
    }

    @Override
    public List<ResultAppList<Material>> queryBaseContainerMaterielList(String[] containerNumber) {
        List<Material> materialList = sortingAppServiceMapper.queryBaseContainerMaterielList(containerNumber);
        return CustomUtil.QueryResultChange(materialList);
    }

    /**
     * 卸车收货提交
     * @param json 提交数据
     * @param userId
     */
    @Override
    public void addSortingAppReceiving(String json, String userId) {
        Gson gson = new Gson();
        List<ResultAppList<Material>> resultAppList = gson.fromJson(json, new TypeToken<List<ResultAppList<Material>>>() {}.getType());
        for (ResultAppList<Material> materialResultAppList : resultAppList) {
            //根据容器ID查询车辆ID,司机ID
            TransitLoading transitLoading = sortingAppServiceMapper.queryCarIdByContainer(materialResultAppList.getPsId());
            List<Material> materialList = materialResultAppList.getList();
            SortReceiving sortReceiving = new SortReceiving();
            //车辆ID
            sortReceiving.setVehicleId(transitLoading.getCid());
            //接收人员
            sortReceiving.setReceiveBy(Long.parseLong(userId));
            //司机ID
            sortReceiving.setDriverId(transitLoading.getDid());
            //创建人员
            sortReceiving.setCreateBy(userId);
            sortReceivingMapper.insert(sortReceiving);
            for (Material material : materialList) {
                //添加到详细表中
                SortReceivingDetail sortReceivingDetail = new SortReceivingDetail();
                //容器ID
                sortReceivingDetail.setContainerId(Long.parseLong(materialResultAppList.getPsId()));
                //容器编号
                sortReceivingDetail.setCode(materialResultAppList.getNewPsnumber());
                //收货ID
                sortReceivingDetail.setReceivingId(sortReceiving.getReceivingId());
                //物料ID
                sortReceivingDetail.setMaterielId(material.getMaId());
                //数量
                sortReceivingDetail.setQuantity(material.getQuantity());
                //旧数量
                sortReceivingDetail.setOldQuantity(material.getUserQuantity());
                //喷涂要求
                sortReceivingDetail.setSprayingRequirements(material.getMaSprayingRequirements());
                //紧急程度
                sortReceivingDetail.setEmergencyLevel(material.getUrgent());
                sortReceivingDetailMapper.insert(sortReceivingDetail);
                //更改容器装载数量以及装载的状态
                String remark2 = "FJ-01";
                sortReceivingDetailMapper.updateContainerStareQuantity(materialResultAppList.getPsId(),material.getMaId(),material.getQuantity(),userId,remark2);
                //更改指令单状态-tostare -- 2已收货
                sortReceivingDetailMapper.updateTransitOrderStatus(material.getToId(),userId);
                //更改容器装载记录表状态
                sortReceivingDetailMapper.updateTransitOrderRecordStatus(materialResultAppList.getPsId(),material.getMaId());
            }
        }
    }


    /**
     * 查询框编号
     * @return
     */
    @Override
    public List<Container> queryBaseContainerNumber() {
        return sortingAppServiceMapper.queryBaseContainerNumber();
    }

    @Override
    public List<WarehousesRegionLocation> queryBaseWarehousesRegionLocationNumber(String typeNumber) {
        return sortingAppServiceMapper.queryBaseWarehousesRegionLocationNumber(typeNumber);
    }

    @Override
    public void addSoringFrame(String libraryId, String containerIds, String userId) {
        List<String> stringContainerId = JSON.parseArray(containerIds,String.class);
        Long libraryIdLong = Long.parseLong(libraryId);
        Long userIdLong = Long.parseLong(userId);
        for (String containerId : stringContainerId) {

            //验收库存是否存在
            CustomUtil.verifyStockContainer(containerId,sortReceivingMapper);

            Long containerIdLong = Long.parseLong(containerId);
            SortFrame sortFrame = new SortFrame();
            sortFrame.setReceivingId(23L);
            //库位ID
            sortFrame.setLibraryId(libraryIdLong);
            //容器ID
            sortFrame.setContainerId(containerIdLong);
            //接收人员
            sortFrame.setReceiveBy(userIdLong);
            //接收人员
            sortFrame.setCreateBy(userId);
            sortingStockService.save(sortFrame);
            //提交之后,更改收货详细的状态
            QueryWrapper<SortReceivingDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status",0).eq("container_id",containerId);
            SortReceivingDetail sortReceivingDetail = new SortReceivingDetail();
            sortReceivingDetail.setStatus("1");
            sortReceivingDetailMapper.update(sortReceivingDetail,queryWrapper);

            //装载表改状态
            sortReceivingDetailMapper.updateContainerStareStatus(containerIdLong,userId,libraryIdLong);
        }
    }

    @Override
    public List<Container> querySortingFrameNumber() {
        return sortingStockMapper.querySortingFrameNumber();
    }

    @Override
    public void addSortingOutStock(String libraryId, String containerIds, String userId) {
        List<String> stringContainerId = JSON.parseArray(containerIds,String.class);
        Long userIdLong = Long.parseLong(userId);
        for (String containerId : stringContainerId) {
            //验收容器是否库存
            CustomUtil.verifyStockContainerExceptFj(containerId,sortReceivingMapper);
            Long containerIdLong = Long.parseLong(containerId);
            SortFrame sortFrame = new SortFrame();
            sortFrame.setReceivingId(23L);
            //流程
            sortFrame.setRemark(libraryId);
            //状态
            sortFrame.setStatus("2");
            //操作人员
            sortFrame.setUpdateBy(userId);
            sortFrame.setUpdateDate(new Timestamp(System.currentTimeMillis()));
            QueryWrapper<SortFrame> updateWrapper = new QueryWrapper<>();
            updateWrapper.eq("container_id",containerIdLong).eq("status",0L);
            sortingStockService.update(sortFrame,updateWrapper);
            //sortReceivingDetailMapper.updateContainerStareStatus(containerIdLong,userId,null);
        }
    }

    @Override
    public List<ResultAppList<Material>> queryBaseContainerMaterielListAndEmpty(String[] psNumbers) {
        List<ResultAppList<Material>> newResultAppListList = new ArrayList<>();
        List<Material> materialList = sortingAppServiceMapper.queryBaseContainerMaterielList(psNumbers);
        List<ResultAppList<Material>> resultAppListList = CustomUtil.QueryResultChange(materialList);
        List<ResultAppList<Material>> resultAppListList2 = sortingAppServiceMapper.queryBaseContainerMaterielListAndEmpty(psNumbers);
        newResultAppListList.addAll(resultAppListList);
        newResultAppListList.addAll(resultAppListList2);
        return newResultAppListList;
    }

    /**
     * 转运
     * @param psnumber
     * @return
     */
    @Override
    public List<ResultAppList<Material>> addSortingOutMaterielList(String psnumber) {
        String[] strings = psnumber.split(",");
        List<String> strings1 = new ArrayList<>();
        String[] str = new String[20];
        List<Container> containers = sortingStockMapper.querySortingFrameNumber();
        for (Container container : containers) {
            strings1.add(container.getCnumber());
        }
        for (int i = 0; i < strings.length; i++) {
            if (strings1.contains(strings[i])){
                str[i] = strings[i];
            }
        }
        List<Material> materialList = sortingAppServiceMapper.queryBaseContainerMaterielList(str);
        return CustomUtil.QueryResultChange(materialList);
    }

    @Override
    public List<ResultAppList<Material>> querySortingReceivingNumberMaterielList(String psnumber) {
        String[] strings = psnumber.split(",");
        List<String> strings1 = new ArrayList<>();
        String[] str = new String[20];
        List<Container> containers = sortingAppServiceMapper.queryBaseContainerNumber();
        for (Container container : containers) {
            strings1.add(container.getCnumber());
        }
        for (int i = 0; i < strings.length; i++) {
            if (strings1.contains(strings[i])){
                str[i] = strings[i];
            }
        }
        List<Material> materialList = sortingAppServiceMapper.queryBaseContainerMaterielList(str);
        return CustomUtil.QueryResultChange(materialList);
    }
}
